#include "media_list.h"
#include "thr_list.h"
#include "proto.h"

static pthread_mutex_t listmut = PTHREAD_MUTEX_INITIALIZER;

void *thr_list_create(void *nothing)
{
        uint16_t num;
        uint16_t cur = 0;
        int i;
        uint16_t save; 
        uint16_t size = 0;
        uint16_t count = 0;
        ch_list *ptr;    // 数据来源地址 
        struct msg_list_st  *rbuf_list;  //  发送的数据包 结构体地址

        ptr = mlib_getchnlist();   // ruturn value
        {
                if(ptr == NULL)
                {
                        perror("mlib_getchnlist()");
                        exit(1);
                }
        }
        

        num = ptr->size;
        struct list_entry_st **entry;  // 存放每个包数据的地址
		entry = malloc(sizeof(struct list_entry_st *)*num);

        for(i = 0;i < num;i++)
        {
                size = ptr->list[i]->size + sizeof(struct list_entry_st) - 1;
                entry[i] = malloc(size);
                if(entry[i] == NULL)
                {
                      perror("malloc()\n");
                      exit(1);
                }
                entry[i]->chnid = i+1;
                entry[i]->len = size;
                memcpy(entry[i]->desc,ptr->list[i]->data,ptr->list[i]->size);
                count += size;
                size = 0;
		}

		size = count + 2;
		rbuf_list = malloc(size);

        rbuf_list->chnid = htons(CHNID_LIST);
        for(i = 0;i < num;i++)
        {
                entry[i]->chnid = htons(entry[i]->chnid);
                save = entry[i]->len;
                entry[i]->len = htons(entry[i]->len);

               if(i != 0)
                memcpy(((((char *)(&rbuf_list->entry[0]))+cur)),entry[i],save);

               else
               {
                   memcpy(&rbuf_list->entry[i],entry[i],save);
               }

                cur += save;

        }

        cur = 0;

        while(1)
        {       
                pthread_mutex_lock(&listmut);
                if(sendto(sd,(void *)rbuf_list,size,0,(void *)&raddr,sizeof(raddr)) < 0)
                {
                        exit(1);
                }
                pthread_mutex_unlock(&listmut);

                sleep(1);
        }

        free(rbuf_list);
        for(i = 0;i < num;i++)
        {
                free(entry[i]);
        }

        destory_list(ptr);
		free(entry);
		pthread_mutex_destroy(&listmut);


}
